﻿var fs = require('fs');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var api = require('./class/socre_api');
var recharge_api = require('./class/recharge_api');
let withdrawal_api = require('./class/withdrawal_api');
var webGetUser = require('./class/webGetUser');
var appleRecharge = require('./class/appleRecharger');
var bodyParser = require('body-parser');
var gm_api = require('./class/gm_api');
var ml_api = require('./class/ml_api');
var tw_api = require('./class/tw_api');
var guanfang_api = require('./class/guanfang_api');
var dao = require('./dao/dao');
var landlord_race_dao = require('./dao/landlord_race_Dao');
var gameConfig = require('./config/gameConfig');
var log = require("./../util/loginfo").getInstand;
var multer = require('multer');
var multerObj = multer({dest: './static/upload'});
var consolidate = require('consolidate');
var statics = require('express-static');
var updateConfig = require('./class/updateConfig').getInstand;
var shopping_dao = require('./dao/shopping_dao');
var gameInfo = require('./class/game');
var payback_api = require("./class/payback_api");
var await_list = require("./../util/await_list");
var landlord_api = require("./class/landlord_api");
var login_api = require("./class/login_api");
const sms = require("./class/sms.js");

//版本密钥和版本号
var version = "ymymymymym12121212qwertyuiop5656_";
var num = "2.0";
//
// var Pio = require('socket.io-client');
// var Psocket = Pio('http://192.168.1.66:2020');
//
// Psocket.on('connected', function (msg) {
//     log.info("与PHP进行连接......");
//
//     Psocket.emit('GameServerConnect', {})
// })
// Psocket.on('disconnect', function (data) {
//     log.info("登录PHP被断开")
// });

https = require('https');

var privateKey = fs.readFileSync('./ssl/www.gamefit.cc.key').toString();
var certificate = fs.readFileSync('./ssl/www.gamefit.cc.crt').toString();
var client_certificate = fs.readFileSync('./ssl/www.gamefit.cc.csr').toString();

if (privateKey == null || privateKey == '') {
    log.err("please check privateKey ");
    return;
} else if (certificate == null || certificate == '') {
    log.err("please check certificate ");
    return;
} else if (client_certificate == null || client_certificate == '') {
    log.err("please check client_certificate ");
    return;
}

var credentials = { 
    key: privateKey, 
    cert: certificate, 
    ca: client_certificate, 
    requestCert: true, 
    rejectUnauthorized: true
};

var https_server = https.createServer(credentials, app);  // https需要参数
if (https_server == null) {
    log.err("https launch failed!");
    return;
}

app.use(statics('./static/'));

//跨域问题
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});


//网页模板
app.engine('html', consolidate.ejs);
app.set('views', 'template');
app.set('view engine', 'html');

app.use(bodyParser());

await_list.StartInterval(1000);
app.get('/Activity/gameuse', function (req, res) {
    try {
        log.info("php /Activity/gameuse act == " + req.query.act);
        var options = {req: req, res: res};
        await_list.PushTask(api, options);
    } catch (error) {
        log.err("/Activity/gameuse " + error);
    }
});

//app.use('/logitech',require('./routes/login/logitech.js')());
//网页接口
//app.use('/index',require('./routes/login/login.js')());
//app.use('/shopping',require('./routes/login/shopp.js')());
//app.use('/PersonalCenter',require('./routes/login/PersonalCenter.js')());

//验证充值
app.post('/apple', function (req, res_s) {
    try {
        appleRecharge(req, function (sendStr) {
            res_s.send(sendStr)
        });
    } catch (error) {
        log.err(error);
    }
});


app.get('/logitech', function (req, res) {
    try {
        var Cun = updateConfig.getUpdateCoifig();
        res.send(Cun);
    } catch (error) {
        log.err(error);
    }
});

//充值相关接口
app.get('/recharge', function (req, res) {
    try {
        recharge_api(req, function (sendStr) {
            res.send(sendStr)
        });
    } catch (error) {
        log.err(error);
    }
});

//充值支付宝相关接口
app.get('/rechargeZhifuBao', function (req, res) {
    try {
        //wap
        if (req.query.payType) {
            tw_api.rechargeZhifuBao(req, function (result, url, sendStr) {
                if (result) {
                    res.redirect(url);
                } else {
                    res.send(sendStr);
                }
            });
        } else {
            guanfang_api.rechargeZhifuBao(req, function (result, url, sendStr) {
                if (result) {
                    res.redirect(url);
                } else {
                    res.send(sendStr);
                }
            });
        }
        //皎洁
        // Post.rechargeRfupay(req.query,function(result,url,sendStr){
        //   if (result){
        //     log.info(sendStr)
        //     //res.render('1.ejs',{})
        //     res.type('html');
        //     res.send(sendStr);
        //     //res.redirect(url);
        //   }else{
        //     res.send(sendStr);
        //   }
        // });
    } catch (error) {
        log.err(error);
    }
});

//充值支付宝相关接口
app.get('/rechargeZhifuBaoReturn', function (req, res) {
    try {
        tw_api.rechargeZhifuBaoReturn(req.query, function (result) {
            if (result) {
                res.send("SUCCESS");
            } else {
                res.send("FAIL");
            }
        });
    } catch (error) {
        log.err(error);
    }
});


app.get('/outCoin', function (req, res) {
    try {
        tw_api.outCoin(req.query, function (result) {
            if (result) {
                res.send("SUCCESS");
            } else {
                res.send("FAIL");
            }
        });
    } catch (error) {
        log.err(error);
    }
});


app.post('/gmManage', function (req, res) {
    try {
        log.info("gmManage---");
        var r = null;
        for (var i in req.body) {
            r = JSON.parse(i)
        }
        let key = version + num;
        if (r.key !== key) {
            res.send({rusult: -1});
            return;
        }
        gm_api(r, function (result) {
            res.send(result);
        });
    } catch (error) {
        log.err(error);
    }
});


app.get('/weixinLogin', function (req, res) {
    //res.sendfile('index.html');
    //外部接口
    // weixin(req, function (act, sendStr) {
    //     if (act == 1) {
    //         res.send(sendStr);
    //     } else if (act == 2) {
    //         res.redirect(sendStr);
    //     }
    // });

    //log.info(req.query.a);
    res.send('{"status":0,"msg":"","data":{"accountname":"xiexie","gold":"147587148"}}');
});


app.get('/ml_api', function (req, res) {
    try {
        log.info("/ml_api act == " + req.query.act);
        var options = {req: req, res: res};
        await_list.PushTask(ml_api.get, options);
    } catch (error) {
        log.err("/ml_api error " + error);
    }
});

//商城相关
app.post('/webGetUser', function (req, res) {
    try {
        webGetUser(req, function (sendStr) {
            log.info(sendStr);
            res.send(sendStr);
        });
    } catch (error) {
        log.err(error);
    }
});

//获取充值返利记录
app.get('/getPayBackFeeList', function (req, res) {
    try {
        log.info("getPayBackFeeList");
        payback_api.getPayBackFeeList(req, function (sendStr) {
            log.info(sendStr);
            res.send(sendStr);
        });
    } catch (error) {
        log.err(error);
    }
});

//版本验证
app.post('/checkVersion', function (req, res) {
    // log.info("版本验证")
    try {
        //验证版本
        var r = req.query.key;
        let key = version + num;
        if (r !== key) {
            res.send({code: 0, url: "/"});
            return;
        }
        //res.send({code: 1, url: "http://admin.1topgames.com/tg/"});
        res.send({code: 1, url: "http://122.152.231.98/tg/"});
    } catch (error) {
        log.err(error);
    }
});

//商城相关
app.post('/getShopList', function (req, response) {
    try {
        shopping_dao.selectShopList((res) => {
            response.writeHead(200, {"Content-Type": "text/plain"});
            response.write(JSON.stringify(res));
            response.end();
        });
    } catch (error) {
        log.err(error);
    }
});

app.post('/addShoppingGoods', function (req, response) {
    try {
        let data = {};
        for (let key in req.body) {
            data = JSON.parse(key);
        }
        req.body = data;
    } catch (e) {
        log.warn('addShoppingGoods-json');
    }
    try {
        shopping_dao.insertNewGoods(req.body, (res) => {
            response.writeHead(200, {"Content-Type": "text/plain"});
            response.write(JSON.stringify({result: res}));
            response.end();
        });
    } catch (error) {
        log.err(error);
    }
});

app.post('/delShoppingGoods', function (req, response) {
    try {
        let data = {};
        for (let key in req.body) {
            data = JSON.parse(key);
        }
        req.body = data;
    } catch (e) {
        log.warn('delShoppingGoods-json');
    }
    try {
        shopping_dao.delGoods(req.body, (res) => {
            response.writeHead(200, {"Content-Type": "text/plain"});
            response.write(JSON.stringify({result: res}));
            response.end();
        });
    } catch (error) {
        log.err(error);
    }
});

//购买商品
// app.post('/webShopBuy',function(req,res){
//   webGetUser
//   gameInfo.shopBuy(req,function(sendStr){

//     try{
//       var data = JSON.parse(sendStr);
//       if (!data.status){

//       }
//     }
//     catch(e){
//       log.warn('webGetUser');
//     }
//     log.info(sendStr)
//     res.send(sendStr)
//   })
// })
//获取验证码
app.post('/getSmsCode', function (req, response) {
    try {
        let data = {};
        for (let key in req.body) {
            data = JSON.parse(key);
        }
        req.body = data;
    } catch (e) {
        log.warn('getSmsCode-json');
    }
    try {
        sms.send_shansuma(req.body.phone);
        response.writeHead(200, {"Content-Type": "text/plain"});
        response.write(JSON.stringify({code: 1}));
        response.end();
    } catch (error) {
        log.err(error);
    }
});
//检查验证码
app.post('/checkSmsCode', function (req, response) {
    try {
        let data = {};
        for (let key in req.body) {
            data = JSON.parse(key);
        }
        req.body = data;
    } catch (e) {
        log.warn('checkSmsCode-json');
    }
    try {
        let isCodeRight = sms.verify(req.body.phone, req.body.code); // 返回true/false
        let code = 0;
        if (isCodeRight) {
            code = 1;
        }
        response.writeHead(200, {"Content-Type": "text/plain"});
        response.write(JSON.stringify({code: code}));
        response.end();
    } catch (error) {
        log.err(error);
    }
});


var serverSign = "slel3@lsl334xx,deka";
var gameInfo = require('./class/game').getInstand;
var luck_tree = require('./class/luck_tree').getInstand;
var ServerInfo = require('./config/ServerInfo').getInstand;

gameInfo.setIo(io);

io.on('connection', function (socket) {
    socket.emit('connected', 'connect server');

    //服务器进行连接
    socket.on('GameServerConnect', function (info) {
        try {
            if (info.signCode == serverSign) {
                log.info(info.serverName + " | 服务器连接成功!");
                log.info("游戏Id:" + info.serverId);
                socket.emit('GameServerConnectResult', {resultCode: 1});
                if (info.serverId)
                    ServerInfo.setScoket(info.serverId, socket);
                //log.info(ServerInfo)
            } else {
                log.info("尝试连接服务器失败,密码不对");
            }
        } catch (error) {
            log.err(error);
        }
    });

    socket.on('login', function (user) {
        login_api.Login(socket, user);
    });

    //登录完成之后先进入游戏房间,来自于游戏服务器
    socket.on('LoginGame', function (user) {
        login_api.LoginGame(socket, user);
    });

    //登录完成之后进入俱乐部服务器,来自于游戏服务器
    socket.on('LoginClub', function (user) {
        login_api.LoginClub(socket, user);
    });

    //离线操作
    socket.on('disconnect', function () {
        try {
            //log.info("有人离线");
            if (socket.gm_id) {
                log.info("删除gm_socket");
                delete gameInfo.gm_socket[socket.gm_id]
                return;
            }

            //有人离线
            if (!socket.userId) {
                return
            }

            if (socket.serverGameid) {
                log.info("游戏服务器 -" + ServerInfo.getServerNameById(socket.serverGameid) + "- 已经断开连接");
            }

            log.info("disconnect:" + socket.userId);
            //log.info("************")
            //如果用户还存在的话，删除
            var userInfo = {userId: socket.userId, nolog: true};
            gameInfo.deleteUser(userInfo);
            //gameInfo.deleteUserNoLoginGame(socket.userId);
        } catch (error) {
            log.err(error);
        }
    });

    //有用户离开
    socket.on('userDisconnect', function (_userInfo) {
        try {
            if (_userInfo != null && _userInfo.userId) {
                log.info("userDisconnect: ", _userInfo.userId);
            }
            if (_userInfo.ResultCode) {
                gameInfo.setCleanGameIdByUserId(_userInfo);
                gameInfo.deleteUser(_userInfo);
            } else {
                gameInfo.deleteUserNoLoginGame(_userInfo.userId, 1);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //游戏结算
    socket.on('GameBalance', function (_Info) {
        try {
            if (_Info.signCode == serverSign) {
                gameInfo.GameBalance(_Info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //游戏结算(俱乐部扣房卡用)
    socket.on('GameUpdateGold', function (_Info) {
        try {
            log.info("扣除房卡");
            log.info(_Info);
            if (_Info.signCode == serverSign) {
                gameInfo.GameUpdateGold(_Info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //牌局断线
    socket.on('lineOut', function (_Info) {
        try {
            log.info("lineOut");
            log.info(_Info);
            if (_Info.signCode == serverSign) {
                gameInfo.lineOutSet(_Info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //获得断线
    socket.on('getLineOut', function (_Info) {
        try {
            if (_Info.signCode == serverSign) {
                gameInfo.getLineOutMsg(_Info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //比赛结束
    socket.on('matchEnd', function (_info) {
        try {
            gameInfo.addPrize(_info);
        } catch (error) {
            log.err(error);
        }
    });

    //兑换电话卡
    socket.on("exchange", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('exchangejson');
        }
        try {
            gameInfo.exchange(socket.userId, _info, io);
        } catch (error) {
            log.err(error);
        }
    });

    //赠送游戏币给他人
    socket.on("sendCoin", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('sendCoinjson');
        }

        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.sendCoin(socket, _info);
            } 
        } catch (error) {
            log.err(error);
        }
    });
    //赠送游戏币给他人账号形式
    socket.on("sendCoin2", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('sendCoinjson');
        }

        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.selectUserIdAndSendCoin(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //查询游戏币记录
    socket.on("selectCoinLog", function () {
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.selectCoinLog(socket);
            }
        } catch (error) {
            log.err(error);
        }
    });

    socket.on("selectgetCoinLog", function () {
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.selectgetCoinLog(socket);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //修改游戏币记录状态
    socket.on("updateCoinLogState", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('sendCoinjson');
        }
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.updateCoinLogState(socket, _info);
            } 
        } catch (error) {
            log.err(error);
        }
    });

    //获取邮件
    socket.on("getEmail", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('getEmail');
        }
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.getEmail(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //设置邮件已读
    socket.on("setEmailRead", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('sendCoinjson');
        }
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.setEmailRead(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //领取邮件金币
    socket.on("lqCoin_email", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('sendCoinjson');
        }
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.lqCoin_email(socket, _info);
            }   
        } catch (error) {
            log.err(error);
        }
    });

    //使用点卡
    socket.on("useEXcard", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('useEXcardjson');
        }
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.useEXcard(socket, _info);
            } 
        } catch (error) {
            log.err(error);
        }
    });

    //赠送点卡
    socket.on("sendcard", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('sendcardjson');
        }
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.sendcard(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //查询点卡记录
    socket.on("cardLog", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('cardLogjson');
        }
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.cardLog(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //检测
    socket.on("checkNickName", function (_info) {

        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('checkNickName-json');
        }
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.checkNickName(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //账号检测昵称
    socket.on("checkNickNameByAccount", function (_info) {

        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('checkNickNameByAccount-json');
        }
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.checkNickName2(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //修改昵称
    socket.on("updateNickName", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('updateNickName-json');
        }
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.updateNickName(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //修改头像
    socket.on("updateHeadUrl", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('updateHeadUrl-json');
        }
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.updateHeadUrl(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //修改密码
    socket.on("updatePassword", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('updatePassword-json');
        }
        try {
            if (gameInfo.checkDataPassword(socket, _info)) {
                gameInfo.updatePassword(socket, _info);
            }  
        } catch (error) {
            log.err(error);
        }
    });

    //转正
    socket.on("changeOfficial", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('changeOfficial-json');
        }
        try {
            if (gameInfo.checkData(socket, _info)) {
                gameInfo.changeOfficial(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //银行卡
    socket.on("BankInfo", function (_info) {

        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('BankInfo-json');
        }
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.BankInfo(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //获取自己银行卡
    socket.on("getBank", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('getBank-json');
        }
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.getBank(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //绑定支付宝
    socket.on("bindZhifubao", function (_info) {

        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('bindZhifubao-json');
        }
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.bindZhifubao(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //发验证码
    socket.on("sendbindPhoneNo", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('sendbindPhoneNo-json');
        }

        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.sendbindPhoneNo(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //绑定手机
    socket.on("bindPhone", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('bindPhone-json');
        }
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.bindPhone(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //获取是否有未领取奖品
    socket.on("getPrize", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('getPrize-json');
        }
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.getPrize(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //获得每天任务奖品
    socket.on("getDayPrize", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('getDayPrize-json');
        }
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.getDayPrize(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //获得金币排行榜
    socket.on("getCoinRank", function () {
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.getCoinRank(socket);
            }
        } catch (error) {
            log.err(error);
        }
    });
    //获得钻石排行榜
    socket.on("getDiamondRank", function () {
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.getDiamondRank(socket);
            }
        } catch (error) {
            log.err(error);
        }
    });
    //获得商城商品列表
    socket.on("getShoppingList", function () {
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.getShopping_List(socket);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //获得商城用户收货信息
    socket.on("getShopPlayerInfo", function () {

        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.getShopPlayerInfo(socket);
            }
        } catch (error) {
            log.err(error);
        }

    });

    //更新商城用户收货信息
    socket.on("updateShopPlayerInfo", function (_info) {
        try {
            let data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('updateShopPlayerInfo-json');
        }
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.updateShopPlayerInfo(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //提交商城兑换
    socket.on("requestGetShopItem", function (_info) {
        try {
            let data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('requestGetShopItem-json');
        }

        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.requestGetShopItem(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //获取商城兑换记录
    socket.on("getShouhuoRecord", function () {
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.getShouhuoRecord(socket);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //获得任务信息
    socket.on("getTaskInfo", function () {
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.getTaskInfo(socket);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //获得每日登录奖励
    socket.on("getEveryLogin", function () {
        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                gameInfo.getEveryLogin(socket);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //获取用户鱼虾蟹游戏记录查询
    socket.on('getYXXGameRecord', function (_Info) {
        log.info("大厅获取游戏记录");
        try {
            var data = JSON.parse(_Info);
            if (!data.now_page) {
                data.now_page = 0
            }
        } catch (e) {
            log.warn('getYXXGameRecord-json');
        }

        try {
            yuxiaxie_api.getYXXGameRecord(socket, data);
        } catch (error) {
            log.err(error);
        }
    });


    //游戏服务器的排行
    socket.on("setServerRank", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('setServerRank-json');
        }
        try {
            gameInfo.setServerRank(_info);
        } catch (error) {
            log.err(error);
        }
    });


    socket.on("score_changeLog", function (_info) {
        try {
            gameInfo.insertScore_change_log(_info);
        } catch (error) {
            log.err(error);
        }
    });

    socket.on("insertMark", function (_info) {
        try {
            gameInfo.insertMark(_info);
        } catch (error) {
            log.err(error);
        }
    });
    // socket.on("pre_insertMark", function (_info) {
    //     gameInfo.pre_insertMark(_info);
    // });

    socket.on("pro_change", function (_info) {
        try {
            gameInfo.pro_change(_info);
        } catch (error) {
            log.err(error);
        }
    });

    //游戏服务器的排行
    socket.on("getServerRank", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('getServerRank-json');
        }
        try {
            gameInfo.getServerRank(socket, _info);
        } catch (error) {
            log.err(error);
        }
    });

    //报名
    socket.on('applyMatch', function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('applyMatch-json');
        }
        try {
            gameInfo.ApplyMatch(socket.userId, _info.roomid, socket); 
        } catch (error) {
            log.err(error);
        }
    });

    //喇叭说话
    socket.on('sendMsg', function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('sendMsg-json');
        }
        try {
            gameInfo.sendMsg(socket.userId, _info, io);
        } catch (error) {
            log.err(error);
        }
    });

    //私聊
    socket.on('sendMsgToUser', function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('sendMsgToUser-json');
        }
        try {
            gameInfo.sendMsgToUser(socket, _info);
        } catch (error) {
            log.err(error);
        }
    });

    //获取未收到私聊
    socket.on('getMsgToUser', function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('getMsgToUser-json');
        }
        try {
            gameInfo.getMsgToUser(socket, _info);
        } catch (error) {
            log.err(error);
        }
    });

    //更新聊天记录
    socket.on('updateCharLog', function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('updateCharLog-json');
        }
        try {
            gameInfo.updateCharLog(socket, _info.idList);
        } catch (error) {
            log.err(error);
        }
    });

    //兑奖
    socket.on('scoreOut', function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('getMsgToUser-json');
        }
        try {
            _info.ip = socket.handshake.address;
            log.info(_info);
            if (_info.ip.split(':').length > 0) {
                var ip = _info.ip.split(':')[3];
                if (ip) {
                    _info.ip = ip;
                } else {
                    // _info.ip = "116.196.93.26";
                }
                gameInfo.scoreOut(socket, _info);
            }
        } catch (error) {
            log.err(error);
        }
    });

    //发送聊天给GM
    socket.on('sendMsgToGM', function (_info) {
        log.info("sendMsgToGM");
        if (!socket.userId) {
            log.info("没有用户id")
        }
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            // log.warn('sendMsgToGM-json');
        }
        try {
            gameInfo.sendMsgToGM(socket, _info);
        } catch (error) {
            log.err(error);
        }
    });


    //客服登录
    socket.on('GMLogin', function (_info) {
        log.info("GMLogin");
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            // log.warn('sendMsgToGM-json');
        }
        try {
            var code = "sjfhcnweuqiebncwe2@!5fy&";
            if (_info.code == code) {
                socket.gm_id = _info.gm_id;
                gameInfo.setGMSocket(_info.gm_id, socket)
            }
        } catch (error) {
            log.err(error);
        }
    });


    //获得斗地主比赛记录  个人信息
    socket.on('getLandlordRaceInfo', function (_info) {
        log.info("getLandlordRaceInfo");
        //有人离线
        if (!socket.userId) {
            return
        }
        if (!gameInfo.landload_race_is_start) {
            log.info("比赛场关闭不能查询");
            return;
        }

        landlord_race_dao.query_race_list(function (res, rows) {
            if (res) {
                var race_list = [];
                for (var r in rows) {
                    race_list.push(
                        {
                            play: rows[r].play,
                            win_all: rows[r].win_all,
                            nick_name: rows[r].nick_name,
                            head_url: rows[r].head_url
                        }
                    )

                }

                landlord_race_dao.getBaoMing(socket.userId, function (state, rs) {
                    var bm_score = gameInfo.landload_race_dict["score"];
                    var rss = {};
                    if (rs) {
                        bm_score = rs[0].bm_score;
                        rss = {play: rs[0].play, win_all: rs[0].win_all}
                    }
                    log.info(state);

                    var award = [];
                    var awards = gameInfo.landload_race_dict["awards"];
                    for (var la in awards) {
                        award.push(awards[la]["value"])
                    }

                    socket.emit('getLandlordRaceInfoResult', {
                        result: true,
                        data: state,
                        rows: rss,
                        race_list: race_list,
                        bm_score: bm_score,
                        award: award,
                    });
                })
            }
        })
    });


    //获得斗地主比赛场报名记录
    socket.on('getLandlordBaoMing', function (_info) {
        log.info("getLandlordBaoMing");

        //有人离线
        if (!socket.userId) {
            return;
        }
        if (!gameInfo.landload_race_is_start) {
            log.info("比赛场关闭不能查询");
            return;
        }

        landlord_race_dao.getBaoMing(socket.userId, function (state, rows) {
            socket.emit('getLandlordBaoMingResult', {
                result: true,
                data: state,
                rows: rows,
            });
        });
    });


    //斗地主   比赛场报名
    socket.on('add_Landlord_BaoMing', function (_info) {
        log.info("add_Landlord_BaoMing ");

        try {
            //有人离线
            if (!socket.userId) {
                return
            }
            const user = gameInfo.userList.getUser(socket.userId)
            if (!user) {
                return
            }
            if (!gameInfo.landload_race_is_start) {
                log.info("比赛场关闭不能报名");
                return;
            }
            landlord_race_dao.getBaoMing(socket.userId, function (state, rows) {   //检查是否已经报名了
                if (state) {
                    socket.emit('add_Landlord_BaoMingResult', {
                        result: false,
                        data: 1,
                    });
                    return;
                }

                var baoming_Info = {};
                baoming_Info["userid"] = socket.userId;
                baoming_Info["all_num"] = parseInt(gameInfo.landload_race_dict.total);
                baoming_Info["lost_num"] = parseInt(gameInfo.landload_race_dict.out);
                baoming_Info["bm_score"] = parseInt(gameInfo.landload_race_dict.score);

                const user = gameInfo.userList.getUser(socket.userId)
                user.addgold(-baoming_Info["bm_score"]);

                log.info("-----------------", baoming_Info)
                landlord_race_dao.add_BaoMing(baoming_Info, function (state) {
                    if (state) {
                        log.info("报名成功");
                        socket.emit('add_Landlord_BaoMingResult', {
                            result: true,
                            data: state,
                        });
                    } else {
                        log.info("报名失败");
                        socket.emit('add_Landlord_BaoMingResult', {
                            result: false,
                            data: 2,
                        });
                    }
                });
            });
        } catch (error) {
            log.err(error);
        }
    });

    //获得自己斗地主比赛场记录
    socket.on('getLandlord_race_record', function (_info) {
        log.info("getLandlord_race_record ");
        try {
            //有人离线
            if (!socket.userId) {
                return
            }

            landlord_race_dao.query_race_record(socket.userId, function (state, rows) {
                if (state) {
                    socket.emit('getLandlord_race_recordResult', {
                        result: true,
                        data: state,
                        rows: rows,
                    });
                }
            }); 
        } catch (error) {
            log.err(error);
        }
    });


    //获得斗地主比赛场排行榜
    socket.on('getLandlord_race_sort', function (_info) {
        try {
            landlord_api.getlandlordrace(_info);
        } catch (error) {
            log.err(error);
        }
    });


    //心跳
    socket.on('heartbeat', function () {
        try {
            log.info("heart beat ")
            socket.emit('heartbeatResult');
        } catch (error) {
            log.err(error);
        }
    });


    //摇钱树
    socket.on('LuckTree', function () {
        try {
            if (!socket.userId) {
                return
            }
            var res = luck_tree.lottery(socket.userId);
            socket.emit('LuckTreeResult', res);
        } catch (error) {
            log.err(error);
        }
    });

    //查用户金币数
    socket.on('getPlayerCoin', function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('getPlayerCoin-json');
        }
        try {
            if (!socket.userId) {
                return;
            }
            gameInfo.getUserCoin(socket, _info);
        } catch (error) {
            log.err(error);
        }
    });

    //领取新手卡
    socket.on('newPlayerExchange', function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('newPlayerExchange-json');
        }

        try {
            if (!socket.userId) {
                return;
            }
            let sendData = {
                userId: socket.userId,
                code: _info.key
            };
            ml_api.cdKey(sendData, (res) => {
                log.info(res);
                if (res.code == 1) {
                    socket.emit('newPlayerExchangeResult', {Result: 1, msg: "兑换成功"});
                } else {
                    socket.emit('newPlayerExchangeResult', {Result: 0, msg: res.msg});
                }
            });
        } catch (error) {
            log.err(error);
        }
    });

    //修改银行密码
    socket.on('updateBankpwd', function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('updateBankpwd-json');
        }
        try {
            if (!socket.userId) {
                return;
            }
            gameInfo.getUserBankPwd(socket.userId, (pwd) => {
                if (pwd != _info.pwd) {
                    socket.emit('updateBankpwdResult', {Result: 0, msg: "原始密码错误"});
                    return;
                } else {
                    gameInfo.updateUserBankPwd(socket, _info);
                }
            });
        } catch (error) {
            log.err(error);
        }
    });

    //获取银行分数
    socket.on('getBankScore', function () {
        try {
            if (!socket.userId) {
                return;
            }
            const user = gameInfo.userList.getUser(socket.userId)
            socket.emit('getBankScoreResult', {
                bankScore: user.bankScore
            });
        } catch (error) {
            log.err(error);
        }
    });

    //修改银行分数
    socket.on('updateBankScore', function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('updateBankScore-json');
        }
        try {
            if (!socket.userId) {
                return;
            }
            //判断存取
            if (_info.saveCoin > 0) {
                const user = gameInfo.userList.getUser(socket.userId)
                if (user.getScore() < _info.saveCoin) {
                    socket.emit('updateBankScoreResult', {ResultCode: 0, msg: "金币不足"});
                    return;
                }
                gameInfo.updateBankScore(socket, _info);
            } else {
                //密码判断
                gameInfo.getUserBankPwd(socket.userId, (pwd) => {
                    if (pwd != _info.pwd) {
                        socket.emit('updateBankScoreResult', {Result: 0, msg: "银行密码错误"});
                        return;
                    } else {
                        const user = gameInfo.userList.getUser(socket.userId)
                        if (user.bankScore < -_info.saveCoin) {
                            socket.emit('updateBankScoreResult', {ResultCode: 0, msg: "银行余额不足"});
                            return;
                        }
                        gameInfo.updateBankScore(socket, _info);
                    }
                });
            }
        } catch (error) {
            log.err(error);
        }
    });
    //查询游戏分数
    socket.on('getScoreChange', function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('getScoreChange-json');
        }
        try {
            gameInfo.getScoreChange(socket, _info);
        } catch (error) {
            log.err(error);
        }
    });
    //查询游戏分数2
    socket.on('getCoinLog', function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('getCoinLog-json');
        }
        try {
            gameInfo.getCoinLog(socket, _info);
        } catch (error) {
            log.err(error);
        }
    });
    //用户申请提现
    socket.on("withdraw_apply", function (_info) {
        try {
            var data = JSON.parse(_info);
            _info = data;
        } catch (e) {
            log.warn('withdraw_apply');
        }

        try {
            if (gameInfo.IsPlayerOnline(socket.userId)) {
                var options = {_socket: socket, _info: _info};
                await_list.PushTask(withdrawal_api, options);
            }
        } catch (error) {
            log.err("withdraw_apply " + error);
        }
    });
});

app.set('port', process.env.PORT || 13000);

var server = http.listen(app.get('port'), function () {
    log.info('start at port:', server.address().port);
});

var period = 1000; // 1 second
var noticeflag = true;
var times = 0;

setInterval(function () {
    try {
        var nowDate = new Date();
        //var hours = nowDate.getHours();
        var minute = nowDate.getMinutes();
        var second = nowDate.getSeconds();
        times++;
    
        //比赛时间 8:00 - 24:00
        if (minute % 10 == 0 && second == 0) {
            if (noticeflag)
                gameInfo.sendNotice(io);
            noticeflag = false;
        } else {
            noticeflag = true;
        }
    
        if (times % 3 == 0) {
            //更新机器人登录
            gameInfo.updateLogin();

            //保存用户
            gameInfo.updateOnlineUser();
            gameInfo.updateRobotAll();
        
            //保存log
            gameInfo.score_changeLog();
            gameInfo.diamond_changeLog();
        }

        //计算充值返利
        //if (times % 3 == 0 && hours >= 8 && hours <= 12) {
            //payback_api.calAgentFee();
        //}

        if (times == 30){
            const memoryUsage = process.memoryUsage();
            console.log(`
                内存使用情况:
                - RSS: ${(memoryUsage.rss / 1024 / 1024).toFixed(2)} MB
                - Heap Total: ${(memoryUsage.heapTotal / 1024 / 1024).toFixed(2)} MB
                - Heap Used: ${(memoryUsage.heapUsed / 1024 / 1024).toFixed(2)} MB
                - External: ${(memoryUsage.external / 1024 / 1024).toFixed(2)} MB
            `);
        }
    
        //PostCoin
        if (times == 60) {
            gameInfo.PostCoin();
            times = 0;
        }
    } catch (error) {
        log.err(error);   
    }
}, period);

dao.clenaLineOut();

log.info("登录服务器 v2.0.0");
log.info("服务器启动成功!");
log.info("更新时间:2017.12.17");

